from openpyxl import load_workbook
import json
import pymysql
import csv
import os
import yaml
import inspect
from selenium.webdriver.common.by import By



# 读取yaml做参数化
def read_yaml(file_path):
    """通用 YAML 文件读取函数"""
    abs_path = get_path(file_path)
    with open(abs_path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)

# 读取登录json参数化的数据
def read_login_json():
    # 拼接 login.json 的绝对路径
    current_dir = os.path.dirname(os.path.abspath(__file__))
    json_path = os.path.join(current_dir, '../Data/login.json')

    with open(json_path, 'r', encoding='utf-8') as f:
        return json.load(f)
# 读取csv参数化的数据
def read_csv(file_path):
    """
    读取 CSV 文件并返回字典列表，字典键为表头字段
    :param file_path: CSV 文件路径
    :return: 包含字典的列表，每个字典对应一行数据，键是表头字段名
    """
    abs_path = get_path(file_path)
    data = []
    with open(abs_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)  # 自动以第一行作为表头，解析每行数据为字典
        for row in reader:
            data.append(row)
    return data

# 读取config的数据
def read_config_yaml(yaml_path=None):
    if yaml_path is None:
        # 定位项目根目录，拼接 config/config.yaml 路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(current_dir)
        yaml_path = os.path.join(project_root, 'config', 'config.yaml')

    with open(yaml_path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)

#读取yaml定位的数据
def read_page_yaml(page_name='login_page', yaml_path=None):
    """读取yaml定位的数据

    Args:
        page_name: 要读取的页面模块名，默认为'login_page'
        yaml_path: yaml文件路径，如果为None则自动查找
    """
    if yaml_path is None:
        # 找到项目根目录（根据实际情况调整，这里假设 utils 和 config 平级）
        current_dir = os.path.dirname(os.path.abspath(__file__))
        # 回到项目根目录，再拼 config/page_config.yaml
        project_root = os.path.dirname(current_dir)
        yaml_path = os.path.join(project_root, 'config', 'page_config.yaml')

    with open(yaml_path, 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)[page_name]  # 动态读取指定的页面模块
    return {
        elem: (getattr(By, info['By'].upper()), info['value'])
        for elem, info in config.items()
    }

# 测试用例中调用
def get_path(file_path):
    # 获取当前脚本所在目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接完整路径
    file_path = os.path.join(base_dir, '..', file_path)
    return file_path


# 连接数据库（增删改查）
class Mysql:
    def __init__(self, host, user, password, database, port=3306, charset='utf8mb4'):
        try:
            self.con = pymysql.connect(
                host=host,
                user=user,
                password=password,
                database=database,
                port=port,
                charset=charset,
                autocommit=False  # 关闭自动提交，确保事务一致性
            )
            self.cursor = self.con.cursor()
        except pymysql.Error as e:
            print(f"数据库连接失败: {e}")
            raise

    def select(self, sql, params=None):
        """执行查询操作，返回结果集"""
        try:
            self.cursor.execute(sql, params)
            return self.cursor.fetchall()
        except pymysql.Error as e:
            print(f"查询执行失败: {e}")
            raise

    def execute(self, sql, params=None):
        """执行增删改操作，返回受影响的行数"""
        try:
            self.cursor.execute(sql, params)
            self.con.commit()
            return self.cursor.rowcount
        except pymysql.Error as e:
            self.con.rollback()
            print(f"SQL执行失败: {e}")
            raise

    def executemany(self, sql, params_list):
        """批量执行增删改操作，返回受影响的总行数"""
        try:
            self.cursor.executemany(sql, params_list)
            self.con.commit()
            return self.cursor.rowcount
        except pymysql.Error as e:
            self.con.rollback()
            print(f"批量执行失败: {e}")
            raise

    def close(self):
        """关闭游标和连接"""
        if self.cursor:
            self.cursor.close()
        if self.con:
            self.con.close()

    def __enter__(self):
        """支持 with 语句"""
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """退出 with 语句时自动关闭连接"""
        self.close()
        return False  # 不抑制异常



# excel表用例
class Excel():
    def __init__(self,path,sheetname):
        self.path=load_workbook(path)
        self.sheetname=self.path[sheetname]

    def getdatalist_mul(self):
        datalist=[]
        for line in self.sheetname:
            getlist_mpl=[]
            getlist_mpl.append(line[0].value)
            getlist_mpl.append(line[1].value)
            datalist.append(getlist_mpl)
        datalist.pop(0)
        return datalist




if __name__ == '__main__':
    # 读csv用例
    file_path=r'config/add1.csv'
    dy=Excel(file_path,'add1')
    print(dy.getdatalist_mul())





